#include <fstream>
#include "json/json.h"

#include "Exceptions.h"
#include "Loading.h"

#include "Serialization.h"

namespace data
{
	std::string GetFileContents( std::string filename )
	{
		std::string text;
		std::ifstream file(filename.c_str());

		if(!file.is_open())
			throw ResourceOpenException( filename );
		while( !file.eof() )
		{
			std::string line;
			file >> line;
			text.append(line);
		}
		file.close();
		return text;
	}

	Json::Value Load( std::string filename )
	{
		std::string document = GetFileContents( filename );
		Json::Reader reader;
		Json::Value root;
		bool parsingSuccessful = reader.parse( document, root );
		if( !parsingSuccessful )
			throw ParserException( filename, reader.getFormattedErrorMessages( ) );
		return root;
	}

	Scene* LoadScene( std::string filename )
	{
		Json::Value jScene = Load(filename);
        return DeserializeScene(jScene);
	}

	Map* LoadMap( std::string filename )
	{
		Json::Value jMap = Load(filename);
        return DeserializeMap(jMap);
	}

	Obstacle* LoadObstacle( std::string filename )
	{
		Json::Value jObstacle = Load(filename);
        return DeserializeObstacle(jObstacle);
	}

	CreatureDef* LoadCreatureDef( std::string filename )
	{
		Json::Value jCreatureDef = Load(filename);
        return DeserializeCreatureDef(jCreatureDef);
	}

	DetailDef* LoadDetailDef( std::string filename )
	{
		Json::Value jDetailDef = Load(filename);
        return DeserializeDetailDef(jDetailDef);
	}

	RotorDef* LoadRotorDef( std::string filename )
	{
		Json::Value jRotorDef = Load(filename);
        return DeserializeRotorDef(jRotorDef);
	}
}
